<template>
  <!-- oa系统常用表格 -->
  <!-- selection-change 当多选状态改变时触发 -->
  <!-- 顶部搜索部分 -->
  <div class="headerSearch">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="姓名">
        <el-input v-model="formInline.name" placeholder="请输入员工姓名"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="formInline.status" placeholder="员工状态">
          <el-option v-for="item in $store.state.statusList" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门">
        <el-select v-model="formInline.department" placeholder="员工所在部门">
          <el-option v-for="item in depts" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search(formInline)">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
  <!-- 中间对员工的操作部分 -->
  <div class="employeeOperation">
    <!-- 新增员工 -->
    <div class="insertNewEmployee">
      <el-button type="primary" @click="dialogAddEmployee = true">新增员工</el-button>
    </div>
    <add-employee :dialogState="dialogAddEmployee"
                  :form="form"
                  :statusList="$store.state.statusList"
                  :depts="depts"
                  :formLabelWidth="$store.state.formLabelWidth"
                  :dropLabelWidth="$store.state.dropLabelWidth"></add-employee>
    <!-- 批量删除 -->
    <div class="deleteEmployee">
      <el-button type="danger" @click="open" :disabled="delArr.length===0">批量删除</el-button>
    </div>
  </div>
  <!-- 表格数据展示部分 -->
  <div class="employeeTable">
    <el-table
            ref="multipleTableRef"
            :data="curData"
            border
            style="width: 90%; max-height: 400px;"
            @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="45"></el-table-column>
      <!--<el-table-column property="workerId" label="编号" width="70"></el-table-column>-->
      <el-table-column property="name" label="姓名" width="100"></el-table-column>
      <el-table-column property="dept" label="部门" width="125"></el-table-column>
      <el-table-column property="post" label="岗位" width="125"></el-table-column>
      <el-table-column property="phone" label="手机号码" width="130"></el-table-column>
      <el-table-column property="id" label="身份证号" width="200"></el-table-column>
      <el-table-column property="status" label="状态" width="100"></el-table-column>
      <el-table-column property="entryDate" label="入职时间" width="105"></el-table-column>
      <el-table-column fixed="right" label="操作" width="100">
        <template #default="scope">
          <el-button link type="primary" size="small"
                     @click="updateEmployee(scope.row)">
            编辑
          </el-button>
          <el-button link type="primary" size="small"
                     @click="confirmSingleDelete(scope.row.workerId)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <my-pagination :totalSize="totalSize"
                   :pageSize="pageSize"
                   :cur="cur"
                   :totalPage="totalPage"></my-pagination>
  </div>
  <!-- 编辑员工信息 -->
  <!-- 组件不能命名为dialog -->
  <my-dialog :dialogState="dialogUpdateEmployee"
             :row="row"
             :statusList="$store.state.statusList"
             :depts="depts"
             :formLabelWidth="$store.state.formLabelWidth"
             :dropLabelWidth="$store.state.dropLabelWidth"
             mode="1"></my-dialog>
</template>

<script>
  import MyDialog from '@/components/dialogs/myDialog/MyDialog'
  import AddEmployee from '@/components/dialogs/addEmployee/AddEmployee'
  import MyPagination from '@/components/myPagination/MyPagination'
  import {myMixin} from "../../../plugins/mixin";
  import {getNowDate} from "../../../plugins/utils";
  import { ElMessage } from 'element-plus'

  export default {
    name: "Employee",
    mixins: [myMixin],
    data() {
      return {
        includeDelete: [],
        formInline: {
          name: '', // 输入框用户
          status: '', // 输入框手机号码
          department: '' // 输入框部门
        },
        delArr: [], // 要批量删除员工的编号
        types: ['', '兼职', '全职'], // 可选类型
        dialogAddEmployee: false, // 添加员工对话框可见性
        dialogFormVisible: false, // 表单可见性
        dialogUpdateEmployee: false, // 编辑员工信息对话框可见性
        form: { // 添加员工表单双向绑定变量
          name: '',
          sex: '男',
          phone: '',
          id: '',
          dept: '',
          post: '',
          status: '',
          entryDate: getNowDate(),
          birth: '',
        },
        row: {}
      }
    },
    methods: {
      /* 当多选框状态改变 */
      async handleSelectionChange(arr) {
        this.delArr = arr;
      },
      /* 批量删除 */
      async deleteByIds() {
        const ids = [];
        for (const item of this.delArr) {
          ids.push(item.workerId);
        }
        if (ids.length > 0) {
          let res = await this.$request('/employee/delete', {
            delArr: ids
          });
          await this.showEmployees();
          this.changePage(this.cur);
          /* 批量删除后，请求数据重新显示页面，思考处于非第一页时，如果删除导致当前页数据清空，
           * 如何使得删除后显示页为当前页减1 */
        }
      },
      /* 重置搜索条件 */
      reset() {
        for (const key in this.formInline) {
          this.formInline[key] = "";
        }
      },
      /* 请求服务器数据 */
      async search({name, status, department: dept}) {
        let result = await this.$request("/employee/search", {
          name,
          status,
          dept
        });
        this.tableData = result.data;
        this.changePage(1);
      },
      /* 批量删除确认 */
      open() {
        this.$confirm('此操作将删除信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.deleteByIds();
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
      },
      /* 展示所有员工信息 */
      async showEmployees() {
        const result = await this.$request('/employee/list');
        this.includeDelete = result.data;
        this.tableData = [];
        for (const item of this.includeDelete) {
          if (item.visibility === '2') {
            this.tableData.push(item);
          }
        }
      },
      /* 添加员工 */
      async addEmployee() {
        const worker_id = parseInt(this.includeDelete[this.includeDelete.length - 1].workerId.substr(5));
        // console.log(this.includeDelete.length);
        this.form['workerId'] = 'admin' + String(worker_id + 1);
        let str1 = this.$qs.stringify(this.form);
        await this.$request('/employee/insert?' + str1);
        await this.showEmployees();
        this.changePage(1);
        this.dialogAddEmployee = false;
        this.form = {
          name: '',
          sex: '男',
          phone: '',
          id: '',
          dept: '',
          post: '',
          status: '',
          entryDate: getNowDate(),
          birth: '2000-01-01',
        }
      },
      /* 单个删除确认 */
      confirmSingleDelete(workerId) {
        this.$confirm('此操作将删除信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.singleDelete(workerId);
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
      },
      /* 单个删除 */
      async singleDelete(workerId) {
        let res = await this.$request('/employee/delete', {
          delArr: [workerId]
        });
        await this.showEmployees();
        this.changePage(this.cur);
      },
      /* 编辑员工信息确认 */
      async confirmUpdateEmployee() {
        ElMessage.success({
          message: '员工信息已更新！',
          type: 'success',
        });
        let str = this.$qs.stringify(this.row);
        let res = await this.$request('/employee/update?' + str);
        // console.log(res);
        await this.showEmployees();
        this.changePage(this.cur);
        this.dialogUpdateEmployee = false;
      },
      /* 编辑员工信息 */
      updateEmployee(row) {
        // console.log("click", row);
        if (row.formalDate === "" || row.formalDate == null) {
          row.formalDate = '2099-01-01'
        }
        this.dialogUpdateEmployee = true;
        this.row = row;
      },


    },
    components: {
      MyDialog,
      AddEmployee,
      MyPagination
    },
    async mounted() {
      console.log('Employee.vue created!');
      this.getDepts();
      await this.showEmployees();
      this.curData = this.tableData.slice(0, this.pageSize);
      // MyDialog
      this.$bus.on("confirmOperation", () => {
        this.confirmUpdateEmployee();
      });
      this.$bus.on('changeDialogState', () => {
        this.dialogUpdateEmployee = false;
      });
      // AddEmployee
      this.$bus.on('confirmAddition', () => {
        this.addEmployee();
      });
      this.$bus.on('changeAdditionDialogState', () => {
        this.dialogAddEmployee = false;
      });
      // MyPagination
      this.$bus.on("changePageNumber", (cur) => {
        this.changePage(cur);
      })
    },

  }
</script>

<style scoped>
  .headerSearch {
    margin-top: 8px;
    margin-left: 30px;
  }

  .employeeOperation {
    display: flex;
    margin: 2px 0 20px 30px;
  }

  .insertNewEmployee {
    margin-right: 30px;
  }

  .employeeTable {
    margin-left: 30px;
  }

  .el-pagination {
    --el-pagination-button-bg-color: #ffffff;
  }

  .el-dialog {
    --el-dialog-width: 50%;
  }
</style>